﻿using System.Xml.Linq;

namespace TKT.Lifter.CIM.Lifter.TibcoMsg
{
    public class TibcoMessage<TMessageBody> where TMessageBody : MessageBody, new()
    {
        public MessageHeader Header { get; set; }

        public TMessageBody Body { get; set; }

        public MessageReturnSet ReturnSet { get; set; }

        public TibcoMessage()
        {
            this.Header = new MessageHeader();
            this.Body = new TMessageBody();
            this.ReturnSet = new MessageReturnSet();

            this.Header.MessageName = this.Body.MessageName;
        }

        public void Parse(TIBCO.Rendezvous.Message message)
        {
            TIBCO.Rendezvous.MessageField field = message.GetField("Message");
            if (field == null)
            {
                field = message.GetField("xmlData");
            }
            string strXML = field.Value as string;
            XElement root = XElement.Parse(strXML);
            XElement header = root.Element("Header");
            XElement body = root.Element("Body");
            XElement returnSet = root.Element("Return");
            this.Header.Parse(header);
            this.Body.Parse(body);
            this.ReturnSet.Parse(returnSet);
        }

        public TIBCO.Rendezvous.Message ToMessage()
        {
            TIBCO.Rendezvous.Message message = new TIBCO.Rendezvous.Message();

            XElement xMsg = new XElement("Message");
            xMsg.Add(this.Header.toXElement());
            xMsg.Add(this.Body.ToXElement());
            xMsg.Add(this.ReturnSet.ToXElement());

            TIBCO.Rendezvous.MessageField msgfield = new TIBCO.Rendezvous.MessageField("Message", xMsg.ToString());
            message.AddField(msgfield);

            return message;
        }
    }
}
